<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <div style="margin: 15px">
      <a-form layout="inline">
        <!-- <a-form-item>
        <a-input v-model:value="searchValue" allowClear placeholder="搜索" />
      </a-form-item> -->
        <a-form-item>
          <a-button type="primary" @click="handleCreate">新增 </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleEdit">编辑 </a-button>
        </a-form-item>
        <a-form-item>
          <a-popconfirm title="确认删除吗?" @confirm="handleDelete">
            <a-button type="primary">删除 </a-button>
          </a-popconfirm>
        </a-form-item>
      </a-form>

      <a-tree
        style="margin-top: 20px"
        @select="handleSelect"
        :tree-data="treeData"
        :expanded-keys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        @expand="onExpand"
        :field-names="{ children: 'children', title: 'name', key: 'id' }"
      >
        <template #title="{ name }">
          <span v-if="name.indexOf(searchValue) > -1">
            {{ name.substr(0, name.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ name }}</span>
        </template>
      </a-tree>
      <DictModal v-model:visible="openModal" :data="dictModalData" @ok="handleModalOK" />
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: 'DictTree',
};
</script>
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { getDictAllList, deleteDict } from '/@/api/sys/system';
import DictModal from './DictModal.vue';
const emit = defineEmits(['select']);
const treeData = ref([]);
const originalTreeData = ref([]);
const openModal = ref(false);
const dictModalData = { id: undefined, name: '', parentId: undefined, parentName: '' };
//展开的key
const expandedKeys = ref([]);
//搜索关键字
const searchValue = ref('');
//是否展开树
const autoExpandParent = ref(true);
const selectedNode = ref({ id: undefined, name: '', parentId: undefined });
// 展开收起触发
const onExpand = (keys) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};

async function fetch() {
  let reslut = await getDictAllList();
  treeData.value = [{ id: 0, name: '字典目录', children: reslut }];
  originalTreeData.value = treeData.value;
  expandedKeys.value.push(treeData.value[0]?.id);
}

function handleSelect(keys, e) {
  selectedNode.value = e.selectedNodes[0];
  emit('select', keys[0]);
}

onMounted(() => {
  fetch();
});

const getExpandedKeys = (value, keys, tree) => {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      getExpandedKeys(value, keys, node.children);
    }
    if (node.name.indexOf(value) > -1) {
      keys.push(node.id);
    }
  }
  return keys;
};

//搜索事件
watch(searchValue, (value) => {
  if (!value) return (autoExpandParent.value = false);
  expandedKeys.value = [...getExpandedKeys(value, [], treeData.value), treeData.value[0]?.id];
  autoExpandParent.value = true;
});

function handleCreate() {
  if (!selectedNode.value.id) {
    message.warning('请选择字典');
    return;
  }
  openModal.value = true;
  dictModalData.id = undefined;
  dictModalData.name = '';
  dictModalData.parentId = selectedNode.value.id;
  dictModalData.parentName = selectedNode.value.name;
}

function handleEdit() {
  if (!selectedNode.value.id) {
    message.warning('请选择字典');
    return;
  }
  openModal.value = true;
  dictModalData.id = selectedNode.value.id;
  dictModalData.name = selectedNode.value.name;
  dictModalData.parentId = selectedNode.value.parentId;
  dictModalData.parentName = getNodeName(selectedNode.value.parentId, originalTreeData.value);
}
const getNodeName = (id, data) => {
  let name = '';
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    if (node.id == id) {
      return node.name;
    }
    if (node.children) {
      let child = getNodeName(id, node.children);
      if (child) {
        name = child;
      }
    }
  }
  return name;
};
const handleDelete = async () => {
  if (!selectedNode.value.id) {
    message.warning('请选择字典');
    return;
  }
  const id = selectedNode.value.id;
  await deleteDict({ id: id });
  message.success('删除成功');
  fetch();
};

const handleModalOK = (result) => {
  fetch();
};
</script>
